package com.poi.qianmi.fetch;

import com.poi.qianmi.conver.UserConver;
import com.poi.qianmi.fetch.demo2.handle.ExcelParserHandler;
import com.poi.qianmi.model.User;
import com.poi.qianmi.path.GlobalPath;
import com.poi.qianmi.response.Response;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.*;

/**
 * @Classname Fetch
 * @Description TODO
 * @Date 2019/9/20 2:12 下午
 * @Created by xiaocai
 */
@RestController
public class Fetch {

    @GetMapping("/fetch1/{num}")
    public Map fetch1(@PathVariable("num") int num) {
        long startTime = System.currentTimeMillis();
        List<User> userList = new ArrayList<User>();
        File file = new File(GlobalPath.getInstance(num));
        XSSFWorkbook hssfWorkbook = null;
        try {
            hssfWorkbook = new XSSFWorkbook(new FileInputStream(file));
            //获得第一个sheet页
            XSSFSheet sheet = hssfWorkbook.getSheetAt(0);
            for (Row row : sheet) {
                User user = UserConver.converterTosheet(row);
                userList.add(user);
            }
            long endTime = System.currentTimeMillis();
            return Response.ok(userList.size(), endTime - startTime);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Response.fail();
    }

    @GetMapping("/fetch2/{num}")
    public Map fetch2(@PathVariable("num") int num) {
        long startTime = System.currentTimeMillis();
        File file = new File(GlobalPath.getInstance(num));
        FileInputStream inputStream;
        try {
            inputStream = new FileInputStream(file);
            ExcelParserHandler parse = new ExcelParserHandler().parse(inputStream);
            long endTime = System.currentTimeMillis();
            List<User> userList = parse.getUserList();
            return Response.ok(userList.size(), endTime - startTime);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return Response.fail();
    }
}
